package ca.badenhorst.ourtrition.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import ca.badenhorst.ourtrition.NutriApplication;
import ca.badenhorst.ourtrition.R;
import ca.badenhorst.ourtrition.db.DatabaseHelper;
import ca.badenhorst.ourtrition.model.FoodDescription;
import ca.badenhorst.ourtrition.model.FoodGroup;
import ca.badenhorst.ourtrition.model.Nutrition;
import ca.badenhorst.ourtrition.model.Nutritions;
import ca.badenhorst.ourtrition.model.SampleSize;


public class FoodDescriptionActivity extends Activity {

    private ListView vitaminlv;
    private ListView minerallv;
    private SampleSize size = SampleSize.getDefault();
    private FoodDescription foodDescription;
    private TextView energyV;
    private TextView proteinV;
    private TextView fatV;
    private TextView carbsV;
    private TextView fibreV;
    private TextView transV;
    private TextView satV;
    private TextView polyUnSatV;
    private TextView monoUnSatV;
    private NutriApplication nutriApp;
    private Button ateItBtn;
    private EditText multiplierV;
    private String ndb_no;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        nutriApp = (NutriApplication) this.getApplication();

        setContentView(R.layout.activity_food_description);

        proteinV = (TextView) findViewById(R.id.proteinText);
        fatV = (TextView) findViewById(R.id.fatText);
        carbsV = (TextView) findViewById(R.id.carbsText);
        energyV = (TextView) findViewById(R.id.energyText);
        fibreV = (TextView) findViewById(R.id.fibreText);

        transV = (TextView) findViewById(R.id.transText);
        satV = (TextView) findViewById(R.id.satText);
        polyUnSatV = (TextView) findViewById(R.id.polyunsatText);
        monoUnSatV = (TextView) findViewById(R.id.monounsatText);

        vitaminlv = (ListView) findViewById(R.id.vitaminListView);
        minerallv = (ListView) findViewById(R.id.mineralListView);

        Bundle extras = getIntent().getExtras();
        ndb_no = extras.getString(FoodDescription.NDB_NO);

        new HttpGetFoodDescriptionTask(ndb_no).execute();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                Intent upIntent = getParentActivityIntent();
                if (foodDescription != null) {
                    upIntent.putExtra(FoodGroup.DESCRIPTION, foodDescription.getFoodGroupDesc());
                    upIntent.putExtra(FoodGroup.GROUP_CODE, foodDescription.getFoodGroupCd());
                }
                // This activity is part of this app's task, so simply
                // navigate up to the logical parent activity.
                navigateUpTo(upIntent);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setValue(TextView view, String tag) {
        Nutrition nutrition = foodDescription.getNutritions().getNutrient(tag);
        if (nutrition != null) {
            view.setText(nutrition.getValueAsStringWithWeightWithDailyPercentage(nutriApp, size.getWeightGrams()));
        } else {
            view.setText(R.string.NOT_APPLICABLE);
        }

    }

    private void computeNutritionValues() {
        setValue(proteinV, Nutritions.PROTEIN_TAG);
        setValue(fatV, Nutritions.FAT_TAG);
        setValue(carbsV, Nutritions.CARB_TAG);
        setValue(fibreV, Nutritions.FIBRE_TAG);
        setValue(transV, Nutritions.FAT_TRANS_TAG);
        setValue(satV, Nutritions.FAT_SAT_TAG);
        setValue(polyUnSatV, Nutritions.FAT_POLY_UN_SAT_TAG);
        setValue(monoUnSatV, Nutritions.FAT_MONO_UN_SAT_TAG);

        Nutrition kCal = foodDescription.getNutritions().getNutrient(Nutritions.KCAL_TAG);
        energyV.setText(kCal.getValueAsStringWithWeight(size.getWeightGrams(),0));
//        String energyText = "";
//        boolean hasKCal = false;
//        if (kCal != null) {
//            energyText = kCal.getValueAsStringWithWeight(size.getWeightGrams());
//            hasKCal = true;
//        }
//        Nutrition kJol = foodDescription.getNutritions().getNutrient(Nutritions.KJOULES_TAG);
//        if (kJol != null) {
//            if (hasKCal) {
//                energyText += "/" + kJol.getValueAsStringWithWeight(size.getWeightGrams());
//            } else {
//                energyText += kJol.getValueAsStringWithWeight(size.getWeightGrams());
//            }
//        }
//        energyV.setText(energyText);

        Set vits = foodDescription.getNutritions().getVitamins();
        Nutrition[] vitsArray = new Nutrition[vits.size()];
        vits.toArray(vitsArray);
        vitaminlv.setAdapter(new FoodArrayAdapter(
                FoodDescriptionActivity.this,
                R.layout.food_description_general_list, vitsArray));


        Set mins = foodDescription.getNutritions().getMinerals();
        Nutrition[] minsArray = new Nutrition[mins.size()];
        mins.toArray(minsArray);
        minerallv.setAdapter(new FoodArrayAdapter(
                FoodDescriptionActivity.this,
                R.layout.food_description_general_list, minsArray));

    }

    public class FoodArrayAdapter extends ArrayAdapter<Nutrition> {
        private final int layoutResourceId;
        private final Context mContext;
        private final Nutrition[] data;

        public FoodArrayAdapter(Context mContext, int layoutResourceId, Nutrition[] data) {

            super(mContext, layoutResourceId, data);

            this.layoutResourceId = layoutResourceId;
            this.mContext = mContext;
            this.data = data;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

        /*
         * The convertView argument is essentially a "ScrapView" as described is Lucas post
         * http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/
         * It will have a non-null value when ListView is asking you recycle the row layout.
         * So, when convertView is not null, you should simply update its contents instead of inflating a new row layout.
         */
            if(convertView==null){
                // inflate the layout
                LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
                convertView = inflater.inflate(layoutResourceId, parent, false);
            }

            // object item based on the position
            Nutrition nutrition = data[position];

            // get the TextView and then set the text (item name) and tag (item ID) values
            TextView nameTextView = (TextView) convertView.findViewById(R.id.food_left);
            TextView valueTextView = (TextView) convertView.findViewById(R.id.food_right);
            nameTextView.setText(nutrition.getDescription());
            valueTextView.setText(nutrition.getValueAsStringWithWeightWithDailyPercentage(nutriApp, size.getWeightGrams()));

            return convertView;

        }

    }
    private class HttpGetFoodDescriptionTask extends AsyncTask<Void, Void, FoodDescription> {

        private final String ndbNo;
        private final SQLiteDatabase db;

        public HttpGetFoodDescriptionTask(String ndb_no) {
            ndbNo = ndb_no;
            DatabaseHelper helper = new DatabaseHelper(FoodDescriptionActivity.this);
            db = helper.getReadableDatabase();
        }

        @Override
        protected FoodDescription doInBackground(Void... params) {
            String[] selectionArgs = {ndbNo};

            FoodDescription foodDescription = new FoodDescription();

//            return db.rawQuery("select id as _id, ndb_no, description from foods where food_group=?", selectionArgs);
            Cursor cursor = db.rawQuery("select ndb_no, name,description,f.food_group_cd from foods f, food_groups fg where fg.groupCd=f.food_group_cd and ndb_no = ?", selectionArgs);
            if (cursor.moveToNext()) {
                foodDescription.setNdbNo(cursor.getString(0));
                foodDescription.setLongDesc(cursor.getString(1));
                foodDescription.setFoodGroupDesc(cursor.getString(2));
                foodDescription.setFoodGroupCd(cursor.getString(3));

                foodDescription.setNutritions(getNutrition(selectionArgs));
                foodDescription.setSampleSizes(getSampleSizes(selectionArgs));
            }

            return foodDescription;
        }

        protected void onPostExecute(FoodDescription result) {
            foodDescription = result;
            ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
            progressBar.setVisibility(View.INVISIBLE);
            TextView titleV = (TextView) findViewById(R.id.foodTitleText);
            titleV.setText(result.getLongDesc());
            TextView foodGroupV = (TextView) findViewById(R.id.foodGroupText);
            foodGroupV.setText(result.getFoodGroupDesc());

            TextView vitLbl = (TextView) findViewById(R.id.vitaminsLbl);
            TextView minLbl = (TextView) findViewById(R.id.mineralsLbl);


            vitLbl.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (vitaminlv.getVisibility() == View.GONE) {
                        vitaminlv.setVisibility(View.VISIBLE);
                    } else {
                        vitaminlv.setVisibility(View.GONE);
                    }
                }
            });

            minLbl.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (minerallv.getVisibility() == View.GONE) {
                        minerallv.setVisibility(View.VISIBLE);
                    } else {
                        minerallv.setVisibility(View.GONE);
                    }
                }
            });

            Spinner sizelv = (Spinner) findViewById(R.id.servingSizeSpinner);
            ArrayAdapter adapter = new ArrayAdapter(
                    FoodDescriptionActivity.this,
                    android.R.layout.simple_spinner_item, result.getSampleSizesWithDefault());
            // Specify the layout to use when the list of choices appears
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            sizelv.setAdapter(adapter);

            sizelv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    size = (SampleSize) parent.getItemAtPosition(position);
                    computeNutritionValues();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            computeNutritionValues();
        }

        private List<SampleSize> getSampleSizes(String[] selectionArgs) {
            List<SampleSize> sizes = new ArrayList<SampleSize>();

            Cursor cursor = db.rawQuery("select ndb_no, seq, amount, description, weight_gms from sizes s where s.ndb_no=? order by seq", selectionArgs);
            while (cursor.moveToNext()) {
                SampleSize size = new SampleSize();
                size.setNdbNo(cursor.getString(0));
                size.setSequence(cursor.getInt(1));
                size.setAmount(cursor.getDouble(2));
                size.setDescription(cursor.getString(3));
                size.setWeightGrams(cursor.getDouble(4));
                sizes.add(size);
            }

            return sizes;
        }

        private Nutritions getNutrition(String[] selectionArgs) {
            Nutritions nutritions = new Nutritions();

            Cursor cursor = db.rawQuery("select ndb_no, n.nutr_no,description,tag,amount,units from food_nutrition fn, nutritions n where n.nutr_no=fn.nutr_no and fn.ndb_no=?", selectionArgs);
            while (cursor.moveToNext()) {
                Nutrition nutrition = new Nutrition();
                nutrition.setNdbNo(cursor.getString(0));
                nutrition.setNutrNo(cursor.getString(1));
                nutrition.setDescription(cursor.getString(2));
                nutrition.setTagname(cursor.getString(3));
                nutrition.setValue(cursor.getDouble(4));
                nutrition.setUnits(cursor.getString(5));
                nutritions.add(nutrition);
            }

            return nutritions;
        }
    }

}



